package com.maltys.dynamicdatasource.common.aspect;


import com.maltys.dynamicdatasource.common.annotation.CurrentDataSource;
import com.maltys.dynamicdatasource.common.context.DynamicDataSourceContext;
import com.maltys.dynamicdatasource.common.enums.DataSourceEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class DynamicDataSourceAspect {
    /**
     * 扫描有CurrentDataSource注解的方法
     */
    @Pointcut("@annotation(com.maltys.dynamicdatasource.common.annotation.CurrentDataSource)")
    public void pointcut() {}


    @Before("pointcut()")
    public void dynamicDataSource(JoinPoint joinPoint) throws Throwable {
        // 获取注解标注的数据源
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        CurrentDataSource currentSource = methodSignature.getMethod().getAnnotation(CurrentDataSource.class);

        // 获取当前方法标记的数据源
        DataSourceEnum dataSourceEnum = currentSource.currentSource();
        String key = dataSourceEnum.getKey();
        // 设置动态数据源
        DynamicDataSourceContext.setContextKey(key);
    }
    @After("pointcut()")
    public void after(){
        // 移除动态数据源
        DynamicDataSourceContext.removeContextKey();
    }
}
